import { getData } from '@/services';
import COS from 'cos-js-sdk-v5';

export default function useDownload() {
  const download = async key => {
    const res = await getData(`/api/auth/cos/getKeyAndCredentials`);
    const { tmpSecretId, tmpSecretKey, sessionToken, startTime, expiredTime, bucket, region } =
      res.data;

    const cos = new COS({
      getAuthorization: async function (options, callback) {
        callback({
          TmpSecretId: tmpSecretId,
          TmpSecretKey: tmpSecretKey,
          SecurityToken: sessionToken,
          StartTime: startTime,
          ExpiredTime: expiredTime,
          ScopeLimit: true,
        });
      },
    });

    cos.getObjectUrl(
      {
        Bucket: bucket,
        Region: region,
        Key: key,
      },
      function (err, data) {
        if (err) return console.log(err);
        const downloadUrl =
          data.Url +
          (data.Url.indexOf('?') > -1 ? '&' : '?') +
          'response-content-disposition=attachment';
        window.open(downloadUrl);
      },
    );
  };
  const getFileName = filePath => {
    if (!filePath) return '';
    const parts = filePath.split('-');
    return parts[parts.length - 1];
  };


  return {
    download,
    getFileName
  };
}
